package com.ht.baselibs.ui.base;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.ht.baselibs.R;
import com.ht.baselibs.thread.CompressPhotoThread;
import com.ht.baselibs.ui.widget.jsbridge.BridgeHandler;
import com.ht.baselibs.ui.widget.jsbridge.BridgeWebView;
import com.ht.baselibs.utils.ImageUtil;
import com.ht.baselibs.utils.MyWebChomeClient;
import com.ht.baselibs.utils.PermissionUtil;
import com.ht.baselibs.utils.SharedPreferencesUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by huangtao on 16/10/19.
 */

public abstract class BaseWebViewActivity extends BaseActivity implements MyWebChomeClient.OpenFileChooserCallBack {

    public static final String URL = "url";
    public static final String TITLE = "title";
    public static final String LEFTIMAGE = "left_image";
    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int FILECHOOSER_RESULTCODE = 2;
    private Uri imageUri;
    private BridgeWebView mWebView;

    private String mUrl;
    private String mCenterTitle;
    private boolean leftTitleImage;

    private static final String TAG = "BaseWebViewActivity";

    private static final int REQUEST_CODE_PICK_IMAGE = 0;
    private static final int REQUEST_CODE_IMAGE_CAPTURE = 1;

    private Intent mSourceIntent;
    private ValueCallback<Uri> mUploadMsg;
    public ValueCallback<Uri[]> mUploadMsgForAndroid5;
    // permission Code
    private static final int P_CODE_PERMISSIONS = 101;
    private static final String TAKE_PHOTO_PATH = "ht/kqb/photo/LICENCE.png";
    private String sourcePath1;

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initIntentData(Intent callIntent) {
        mUrl = callIntent.getStringExtra(URL);
        mCenterTitle = callIntent.getStringExtra(TITLE);
        leftTitleImage = callIntent.getBooleanExtra(LEFTIMAGE, true);
    }

    @Override
    protected void initTitleBar() {
        if (!TextUtils.isEmpty(mCenterTitle)) {
            mTitleBarView.setTitleText(mCenterTitle);
        }
        if (!leftTitleImage) {
            mTitleBarView.setLeftBtnVisibility(View.GONE);
        }
    }

    @Override
    protected int initContentView() {
        return R.layout.activity_base_webview;
    }

    @Override
    protected void initChildData() {
        mWebView.loadUrl(mUrl);
    }

    @Override
    protected void initChildView() {
        mWebView = (BridgeWebView) findViewById(R.id.activity_base_webview_webview);

        mWebView.setWebChromeClient(new MyWebChomeClient(BaseWebViewActivity.this));
        doWebView();
//        WebSettings settings = mWebView.getSettings();
//        mWebView.setVerticalScrollBarEnabled(true);
//        mWebView.setHorizontalScrollBarEnabled(false);
//        settings.setJavaScriptEnabled(true);
//        settings.setDomStorageEnabled(true);
//        settings.setJavaScriptCanOpenWindowsAutomatically(true);
//        settings.setUseWideViewPort(true);
//        settings.setLoadWithOverviewMode(true);
//        settings.setBlockNetworkImage(false);
//        settings.setUseWideViewPort(true);
//        settings.setLoadWithOverviewMode(true);
//        mWebView.getSettings().setBlockNetworkImage(false);
    }

    @Override
    protected void setChildViewListener() {
        Map<String, BridgeHandler> handlerMap = getHandlers();
        registerHandlerHandlers(handlerMap);
//        mWebView.callHandler("buttons", "", new CallBackFunction() {
//            @Override
//            public void onCallBack(String data) {
//                UIUtils.showToast("dfdfsadf");
//            }
//        });


    }

    private void registerHandlerHandlers(Map<String, BridgeHandler> handlerMap) {
        for (Map.Entry<String, BridgeHandler> entry : handlerMap.entrySet()) {
            mWebView.registerHandler(entry.getKey(), entry.getValue());
        }
    }


    protected abstract Map<String, BridgeHandler> getHandlers();

    private void doWebView() {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    CookieSyncManager.getInstance().sync();
                } else {
                    CookieManager.getInstance().flush();
                }
            }
        });

        fixDirPath();
        // 加载html界面
        // 支持javascript
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDefaultTextEncodingName("utf-8");
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启 DOM storage API 功能
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportMultipleWindows(false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            if (mUploadMsg != null) {
                mUploadMsg.onReceiveValue(null);
            }

            if (mUploadMsgForAndroid5 != null) {         // for android 5.0+
                mUploadMsgForAndroid5.onReceiveValue(null);
            }
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_IMAGE_CAPTURE:
                try {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                        if (mUploadMsg == null) {
                            return;
                        }
//                        String sourcePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                        String sourcePath = ImageUtil.retrievePath(this, mSourceIntent, data);
                        SharedPreferencesUtils.put("source_path", sourcePath);
                        if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
                            Log.e(TAG, "sourcePath empty or not exists.");
                            break;
                        }

                        new CompressPhotoThread(mHandler, sourcePath, 0).start();
//                        Uri uri = Uri.fromFile(new File(sourcePath));
//                        mUploadMsg.onReceiveValue(uri);

                    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        if (mUploadMsgForAndroid5 == null) {        // for android 5.0+
                            return;
                        }

                        String sourcePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                        if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
                            Log.e(TAG, "sourcePath empty or not exists.");
                            break;
                        }
                        new CompressPhotoThread(mHandler, sourcePath, 0).start();

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case REQUEST_CODE_PICK_IMAGE: {
                try {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                        if (mUploadMsg == null) {
                            return;
                        }

                        sourcePath1 = ImageUtil.retrievePath(this, mSourceIntent, data);
//                        String sourcePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                        if (TextUtils.isEmpty(sourcePath1) || !new File(sourcePath1).exists()) {
                            Log.e(TAG, "sourcePath empty or not exists.");
                            break;
                        }
                        new CompressPhotoThread(mHandler, sourcePath1, 1).start();

                    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        if (mUploadMsgForAndroid5 == null) {        // for android 5.0+
                            return;
                        }

                        sourcePath1 = ImageUtil.retrievePath(this, mSourceIntent, data);
//                        String sourcePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                        if (TextUtils.isEmpty(sourcePath1) || !new File(sourcePath1).exists()) {
                            Log.e(TAG, "sourcePath empty or not exists.");
                            break;
                        }

                        new CompressPhotoThread(mHandler, sourcePath1, 1).start();
//                        Uri uri = Uri.fromFile(new File(sourcePath1));
//                        mUploadMsgForAndroid5.onReceiveValue(new Uri[]{uri});
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }

    @Override
    public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType) {
        mUploadMsg = uploadMsg;
        showOptions();
    }

    @Override
    public boolean openFileChooserCallBackAndroid5
            (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
        mUploadMsgForAndroid5 = filePathCallback;
        showOptions();

        return true;
    }

    @Override
    protected void handleMessage(BaseActivity context, Message msg) {

        switch (msg.what) {
            case 300:
                String sourcePath = "";
                switch ((int) msg.obj) {
                    case 0:

                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                            sourcePath = SharedPreferencesUtils.getString("source_path", "");
                            Uri uri = Uri.fromFile(new File(sourcePath));
                            mUploadMsg.onReceiveValue(uri);
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            if (mUploadMsgForAndroid5 == null) {        // for android 5.0+
                                return;
                            }
                            sourcePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                            Uri uri = Uri.fromFile(new File(sourcePath));
                            mUploadMsgForAndroid5.onReceiveValue(new Uri[]{uri});
                        }
                        break;
                    case 1:
                        sourcePath = sourcePath1;
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                            if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
                                Log.e(TAG, "sourcePath empty or not exists.");
                                break;
                            }
                            Uri uri = Uri.fromFile(new File(sourcePath));
                            mUploadMsg.onReceiveValue(uri);
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            if (mUploadMsgForAndroid5 == null) {        // for android 5.0+
                                return;
                            }
                            Uri uri = Uri.fromFile(new File(sourcePath));
                            mUploadMsgForAndroid5.onReceiveValue(new Uri[]{uri});
                        }
                        break;
                }


                break;
        }
    }


    // 重写返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mWebView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {
            mWebView.goBack(); // goBack()表示返回webView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void showOptions() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setOnCancelListener(new DialogOnCancelListener());

        alertDialog.setTitle("请选择操作");
        // gallery, camera.
        String[] options = {"相册", "拍照"};

        alertDialog.setItems(options, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            if (PermissionUtil.isOverMarshmallow()) {
                                if (!PermissionUtil.isPermissionValid(BaseWebViewActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                                    Toast.makeText(BaseWebViewActivity.this,
                                            "请去\"设置\"中开启本应用的图片媒体访问权限",
                                            Toast.LENGTH_SHORT).show();

                                    restoreUploadMsg();
                                    requestPermissionsAndroidM();
                                    return;
                                }

                            }

                            try {
                                mSourceIntent = ImageUtil.choosePicture();
                                startActivityForResult(mSourceIntent, REQUEST_CODE_PICK_IMAGE);
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(BaseWebViewActivity.this,
                                        "请去\"设置\"中开启本应用的图片媒体访问权限",
                                        Toast.LENGTH_SHORT).show();
                                restoreUploadMsg();
                            }

                        } else {
                            if (PermissionUtil.isOverMarshmallow()) {
                                if (!PermissionUtil.isPermissionValid(BaseWebViewActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                    Toast.makeText(BaseWebViewActivity.this,
                                            "请去\"设置\"中开启本应用的图片媒体访问权限",
                                            Toast.LENGTH_SHORT).show();

                                    restoreUploadMsg();
                                    requestPermissionsAndroidM();
                                    return;
                                }

                                if (!PermissionUtil.isPermissionValid(BaseWebViewActivity.this, Manifest.permission.CAMERA)) {
                                    Toast.makeText(BaseWebViewActivity.this,
                                            "请去\"设置\"中开启本应用的相机权限",
                                            Toast.LENGTH_SHORT).show();

                                    restoreUploadMsg();
                                    requestPermissionsAndroidM();
                                    return;
                                }
                            }

                            try {

                                File file = new File(Environment.getExternalStorageDirectory(), TAKE_PHOTO_PATH);

//                                File file=new File(Environment.getExternalStorageDirectory(), "/UploadImage/"+System.currentTimeMillis() + ".jpg");
                                if (!file.getParentFile().exists()) file.getParentFile().mkdirs();

                                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                                    mSourceIntent = ImageUtil.takeBigPicture();
                                    startActivityForResult(mSourceIntent, REQUEST_CODE_IMAGE_CAPTURE);
                                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                    mSourceIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                                    通过FileProvider创建一个content类型的Uri
                                    imageUri = FileProvider.getUriForFile(BaseWebViewActivity.this, "com.jinkaimen.kqb.fileprovider", file);
                                    mSourceIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                    mSourceIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                                    mSourceIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
                                    startActivityForResult(mSourceIntent, REQUEST_CODE_IMAGE_CAPTURE);
                                }
//

                            } catch (Exception e) {

                                Log.e("ddddddddddd", e.getMessage());
                                e.printStackTrace();
                                Toast.makeText(BaseWebViewActivity.this,
                                        "请去\"设置\"中开启本应用的相机和图片媒体访问权限",
                                        Toast.LENGTH_SHORT).show();

                                restoreUploadMsg();
                            }
                        }
                    }
                }
        );

        alertDialog.show();
    }

    private void fixDirPath() {
        String path = ImageUtil.getDirPath();
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    private class DialogOnCancelListener implements DialogInterface.OnCancelListener {
        @Override
        public void onCancel(DialogInterface dialogInterface) {
            restoreUploadMsg();
        }
    }

    private void restoreUploadMsg() {
        if (mUploadMsg != null) {
            mUploadMsg.onReceiveValue(null);
            mUploadMsg = null;

        } else if (mUploadMsgForAndroid5 != null) {
            mUploadMsgForAndroid5.onReceiveValue(null);
            mUploadMsgForAndroid5 = null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case P_CODE_PERMISSIONS:
                requestResult(permissions, grantResults);
                restoreUploadMsg();
                break;

            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void requestPermissionsAndroidM() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> needPermissionList = new ArrayList<>();
            needPermissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            needPermissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            needPermissionList.add(Manifest.permission.CAMERA);

            PermissionUtil.requestPermissions(BaseWebViewActivity.this, P_CODE_PERMISSIONS, needPermissionList);

        } else {
            return;
        }
    }

    public void requestResult(String[] permissions, int[] grantResults) {
        ArrayList<String> needPermissions = new ArrayList<String>();

        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                if (PermissionUtil.isOverMarshmallow()) {

                    needPermissions.add(permissions[i]);
                }
            }
        }

        if (needPermissions.size() > 0) {
            StringBuilder permissionsMsg = new StringBuilder();

            for (int i = 0; i < needPermissions.size(); i++) {
                String strPermissons = needPermissions.get(i);

                if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(strPermissons)) {
                    permissionsMsg.append("," + getString(R.string.permission_storage));

                } else if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(strPermissons)) {
                    permissionsMsg.append("," + getString(R.string.permission_storage));

                } else if (Manifest.permission.CAMERA.equals(strPermissons)) {
                    permissionsMsg.append("," + getString(R.string.permission_camera));

                }
            }

            String strMessage = "请允许使用\"" + permissionsMsg.substring(1).toString() + "\"权限, 以正常使用APP的所有功能.";

            Toast.makeText(BaseWebViewActivity.this, strMessage, Toast.LENGTH_SHORT).show();

        } else {
            return;
        }
    }

    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }


}